import os.path
import shutil
import redi_messages as please

def copy_file(targetDir, targetFile):
    if not os.path.exists(targetDir): os.makedirs(targetDir)
    shutil.copy2(targetFile, targetDir)

def get_filename(filename):
    lastslash = filename.rfind("/") + 1
    if lastslash < 0: lastslash = 0
    lastdot = filename.rfind(".")
    if lastdot < 0: lastdot = len(filename)

    tablename = filename[lastslash:lastdot].upper()
    return tablename.replace(" ", "_").replace(".", "_")

def dataset_exists(dataset_id):
    if not os.path.exists(dataset_id):
        os.makedirs(dataset_id)

    return not os.path.exists(dataset_id + "/dataset.json")

def is_numeric(val):
    try:
        float(val)
    except ValueError, e:
        return False
    return True

def get_dataType(dataset_id, options, usage, allowed_types):
    dataType = options.dataType

    if dataType is None:
        usages = [usage % (dataset_id,idt) for idt in allowed_types]
        please.say("The magic data type guessing module is broken", "Why don't you try one of these instead?", *usages)
        exit(-1)

    if dataType not in allowed_types:
        usages = [usage % (dataset_id,idt) for idt in allowed_types]
        please.say("It'd be better if you use one of these handy-dandy supported data types:", "   " + ", ".join(allowed_types),
                    "Try one of these:", *usages)
        exit(-1)

    return dataType